package com.google.code.whitetask.old;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class AsyncerManager {
  private static final int CORE_POOL_SIZE = 3;
  private static final int MAXIMUM_POOL_SIZE = CORE_POOL_SIZE * 3;
  private static final long KEEP_ALIVE_TIME_IN_SECOND = 10L;
  private static final int SHUTDOWN_TIMEOUT_IN_SECOND = 5;
  ExecutorService executor = null;

  void init() {
    executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE,
        KEEP_ALIVE_TIME_IN_SECOND, TimeUnit.SECONDS,
        new LinkedBlockingQueue<Runnable>());
  }

  void delegate(Task task, TaskEvent event, TaskContext context) {
    Runnable runnable = new AsyncerTaskThread(task, event, context);
    executor.execute(runnable);
  }

  void shutdownGracefully() {
    executor.shutdown();
    try {
      executor.awaitTermination(SHUTDOWN_TIMEOUT_IN_SECOND, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }
    executor = null;
  }
}
